package cn.jsc.org.service.impl;

import cn.jsc.basic.service.impl.BaseServiceImpl;
import cn.jsc.basic.util.MD5Utils;
import cn.jsc.basic.util.StrUtils;
import cn.jsc.org.domain.Employee;
import cn.jsc.org.mapper.EmployeeMapper;
import cn.jsc.org.service.IEmployeeServiceI;
import cn.jsc.user.domain.LoginInfo;
import cn.jsc.user.mapper.LoginInfoMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 部门服务层
 */
@Service
public class EmployeeServiceImpl extends BaseServiceImpl<Employee> implements IEmployeeServiceI {
    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private LoginInfoMapper loginInfoMapper;

    @Override
    @Transactional
    public void add(Employee employee) {
        //设置employee信息
        String salt = StrUtils.getComplexRandomString(32);
        employee.setSalt(salt);
        String md5pwd = MD5Utils.encrypByMd5(employee.getPassword() + salt);
        employee.setPassword(md5pwd);

        //添加t_logininfo信息
        LoginInfo loginInfo = employee2LoginInfo(employee);
        loginInfoMapper.save(loginInfo);

        //添加employee信息 - 可以设置登陆信息的id
        employee.setLogininfo_id(loginInfo.getId());
        super.add(employee);
    }

    private LoginInfo employee2LoginInfo(Employee employee) {
        LoginInfo loginInfo = new LoginInfo();
        BeanUtils.copyProperties(employee,loginInfo);
        loginInfo.setType(0);//0表示管理员
        return loginInfo;
    }

    @Override
    @Transactional
    public void delete(Long id) {
        //先根据id查employee表，为后面删除t_logininfo的信息做准备
        Employee employee = employeeMapper.loadById(id);

        //删除了t_employee的信息
        super.delete(id);

        //删除t_logininfo的信息
        loginInfoMapper.remove(employee.getLogininfo_id());
    }

    //@TODO - 将来做
    @Override
    @Transactional
    public void update(Employee employee) {
        super.update(employee);
    }
}
